---by alexar, Class (Class= require "middleclass") is need 
---用法：img保存动画的image对象 fx,fy,lx,ly 动画第一像素和最后一个像素位置不包含外框
---offx,offy 动画图片间距
---delay 动画延时 
---count 帧数,如缺省则取最大
---mode 0 循环 1 单次 2 回转

local animation=class and class("ani") or {}

function animation:_new(...)
    local new = {}
	self.__index = self
	setmetatable(new, self)
	new:init(...)
	return new
end

function animation:init(img,fx,fy,w,h,offx,offy,wc,hc,delay,count) 

	self.img=img
	local sw,sh= img:getDimensions()
	
	self.frames={}
    offx = offx or 0
    offy = offy or 0
    wc = wc or 1
    hc = hc or 1
	local stop
    local index=0
	for iy=0,hc-1 do
		for ix=0,wc-1 do
            local x = fx +ix*(w+offx)
            local y = fy +iy*(h+offy)
			local quad = love.graphics.newQuad(x, y, w, h, sw, sh)
			index=index+1
			self.frames[index]=quad
			if count and index+1>count then  stop=true ;break end
		end
		if stop then break end
	end
	self.maxFrame=index
	self.currentFrame=1
	self.mode= 0 --0 for loop  1 for one time 2 for bounce
	self.isRev=false
	self.isPlay=true --0 for stop 1 for play 2 
	self.timer=0
	self.delay=delay or 0.1
    self.flipX = false
	self.frame=self.frames[self.currentFrame]
end


function animation:play()
    self.currentFrame = 1
	self.isPlay=true
end

function animation:resume()
    self.isPlay=true
end

function animation:stop()
	self.isPlay=false
end

function animation:setMode(mode)
	if mode == "loop" then
		self.mode = 0 
	elseif mode == "once" then
		self.mode = 1
	elseif mode == "bounce" then
		self.mode = 2
	end
	self.currentFrame = 1
	self.isPlay = true
end

function animation:update(dt)
	local frame=self.frames[self.currentFrame]
	if self.isPlay then
		self.timer=self.timer+dt
		if self.timer>=self.delay then
			self.timer=0
			if self.isRev then
				self.currentFrame=self.currentFrame-1
				if self.currentFrame<1 then
					if self.mode==0 then
						self.currentFrame=self.maxFrame
						if self.onLoop then self:onLoop() end
					elseif self.mode==1 then
						self.currentFrame=1
						self.isPlay=false
						if self.onEnd then self:onEnd() end
					elseif self.mode==2 then
						self.currentFrame=1
						self.isRev=not self.isRev
						if self.onRev then self:onRev() end
					end
				end
			else
				self.currentFrame=self.currentFrame+1
				if self.currentFrame>self.maxFrame then
					if self.mode==0 then
						self.currentFrame=1
						if self.onLoop then self:onLoop() end
					elseif self.mode==1 then
						self.currentFrame=self.maxFrame
						self.isPlay=false
						if self.onEnd then self:onEnd() end
					elseif self.mode==2 then
						self.currentFrame=self.maxFrame
						self.isRev=not self.isRev
						if self.onRev then self:onRev() end
					end
				end
			end

		end
	end
	self.frame=frame
end

function animation:draw(x,y,rot,scaleX,scaleY,offx,offy)
	love.graphics.draw(self.img,self.frame, x,y,rot,
        (scaleX or 1)*(self.flipX and -1 or 1),scaleY,offx,offy)
end

return animation